#include "mycombobox.h"

MyComboBox::MyComboBox(QWidget *parent)
    :QComboBox(parent)
{
    connect(this, SIGNAL(currentIndexChanged(int)),
            this,SLOT(slot_setPopupType(int)));

    setProperty("Type", "popup");
    setCurrentIndex(-1);
}

void MyComboBox::mouseReleaseEvent(QMouseEvent *e)
{
    QStyleOptionComboBox opt;
    this->initStyleOption(&opt);
    // 此处是获取鼠标按下的坐标对应的子控件
    QStyle::SubControl sc = this->style()->hitTestComplexControl(QStyle::CC_ComboBox, &opt, e->pos(), this);
	
	// 屏蔽右键
    if (e->button() == Qt::RightButton) {
        return;
    }

    if (property("Type") == "close") {
        // 当sc == SC_ComboBoxArrow代表，按下的位置为下拉箭头的位置
        if (e->button() == Qt::LeftButton
                && sc == QStyle::SC_ComboBoxArrow) {
            setCurrentIndex(-1);
        } else {
            QComboBox::showPopup();
        }
        return;
    }

    return QComboBox::mousePressEvent(e);
}

void MyComboBox::mousePressEvent(QMouseEvent *e)
{
    // 此处为了禁止按住拖动时会展开下拉菜单
    Q_UNUSED(e);
    return;
}

void MyComboBox::slot_setPopupType(const int &index)
{
    QString type;
    type = (index == -1 ? "popup" : "close");
    setProperty("Type", type);
    style()->polish(this);
}
